/****************
 *@description: 新建拼团活动  spellTogether/add
 *@author: Xhd
 *@date: 2023-09-07 11:26:31
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from "react";
import { apiPostSpellTogetherAdd } from "@/request/spellTogether";
import { Button, Form, Input, DatePicker, InputNumber, } from 'antd';
import GoBack from '@/components/TheGoBack';
import Goods from './components/Goods';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

class SpellTogetherAdd extends Component {
  constructor() {
    super()
    this.formRef = React.createRef()
    this.GoodsRef = React.createRef()
    this.state = {
      initialValues: {},
      goodsSku: [],
      disabledKeys: [],
      mode: "add"
    }
  }

  componentDidMount() {

  }

  async onFinish() {
    const values = this.formRef.current.getFieldsValue()
    const params = {
      activityName: values.activityName,//活动名称
      startTime: values.activityTime ? dayjs(values.activityTime[0]).format('YYYY-MM-DD HH:mm') : '',//开始时间
      endTime: values.activityTime ? dayjs(values.activityTime[1]).format('YYYY-MM-DD HH:mm') : '',//结束时间
      teamPeriod: values.teamPeriod,
      teamSize: values.teamSize,
      goodsList: values.goods.map(item => {
        return {
          goodsId: item.goodsId,//商品id
          goodsName: item.goodsName,//商品名称
          goodsShowImages: item.goodsShowImages,
          sort: item.killSort,//排序
          skuList: item.skuInfoVos.map(sku => {
            return {
              goodsSkuId: sku.goodsSkuId,//skuId
              skuAttributes: sku.skuAttributes,
              activityStock: sku.a_stock,//活动库存
              activityGoodsSkuPrice: sku.a_price ? sku.a_price * 100 : 0,//活动价格
              activityGoodsSkuOriginalPrice: sku.skuOriginalPrice ? sku.skuOriginalPrice : 0,
              skuStock: sku.skuStock,//库存
              skuCurrentPrice: sku.skuCurrentPrice ? sku.skuCurrentPrice : 0,//日常价格
            }
          })
        }
      })
    }
    apiPostSpellTogetherAdd(params).then(res => {
      if (res.code === 0 && res.data) {
        React.$message({
          type: 'info',
          content: '创建成功'
        })
        this.props.history.goBack(-1)
      };
    })
  }

  disabledDate(current) {
    return current && current < dayjs().startOf('D');
  };
  checkGoods(rules, value, callback) {
    value = this.GoodsRef.current.state.dataSource
    const formValue = this.formRef.current.getFieldsValue()
    let flag = true
    if (Array.isArray(value) && value.length > 0) {
      value.forEach(item => {
        item.killSort_tip = null
        item.skuInfoVos = item.skuInfoVos.map(sku => {
          if (sku.isJoin) { //0 参加  1不参加
            sku.a_stock_tip = null
            sku.a_price_tip = null
            sku.quota_count_tip = null
            sku.virtualCount_tip = null
            return sku
          } else {
            if (item.killSort === null || !item.hasOwnProperty('killSort')) {
              item.killSort_tip = '请填写排序！'
              flag = false
            } else {
              item.killSort_tip = null
            }
          }
          // 校验活动库存
          if (sku.a_stock === null || !sku.hasOwnProperty('a_stock')) {
            sku.a_stock_tip = '请填写活动库存！'
            flag = false
          } else if (sku.a_stock > sku.skuStock && sku.skuStock !== -1) {
            sku.a_stock_tip = '活动库存必须小于等于实际库存值！'
            flag = false
          } else {
            sku.a_stock_tip = null
          }
          if (sku.hasOwnProperty('goodsSurplusSum') || sku.hasOwnProperty('goodsBuySum')) {
            if (sku.a_stock < sku.goodsBuySum) {
              sku.a_stock_tip = '活动库存小于实际已售卖的数量！'
              flag = false
            }
          }
          // 校验活动价
          if (sku.a_price === null || !sku.hasOwnProperty('a_price')) {
            sku.a_price_tip = '请填写活动价！'
            flag = false
          } else if(sku.a_price*100 > sku.skuOriginalPrice ) {
            sku.a_price_tip = '拼团价必须小于等于日常价！'
            flag = false
          }else {
            sku.a_price_tip = null
          }
          // 校验限购件数
          // if (sku.isLimit && (sku.quota_count === null || !sku.hasOwnProperty('quota_count'))) {
          //   sku.quota_count_tip = '请填写限购件数！'
          //   flag = false
          // } else {
          //   sku.quota_count_tip = null
          // }
          // 校验虚拟抢购件数
          // if (sku.virtualCount === null || !sku.hasOwnProperty('virtualCount')) {
          //     sku.virtualCount_tip = '请填写虚拟抢购件数！'
          //     flag = false
          // } else 
          // if (sku.virtualCount !== null && sku.virtualCount >= sku.a_stock && sku.a_stock > 0) {
          //   sku.virtualCount_tip = '虚拟抢购件数必须小于实际活动库存值'
          //   flag = false
          // } else {
          //   sku.virtualCount_tip = null
          // }
          return sku
        })
      })
    }
    if (Array.isArray(value) && value.length > 0) {
      if (value.length < 1) {
        callback('请至少选择1个商品!')
      } else {
        if (flag) {
          callback()
          this.GoodsRef.current.setState({
            dataSource: value
          }, () => {
            this.formRef.current.setFieldsValue({ goods: value })
          })
        }
        if (!flag) {
          this.GoodsRef.current.setState({
            dataSource: value
          })
          callback('请完善数据!')
        }
      }
    } else {
      callback('请添加活动商品!')
    }
  }

  getFieldsValue(key, isCheck) {
    const values = this.formRef.current.getFieldsValue()
    if (!values.activityTime) {
      isCheck && this.formRef.current.validateFields([key])
      return false
    }
    return values.activityTime
  }

  render() {
    const { mode, activityId, initialValues, disabledKeys, } = this.state
    return (<div className="p-layout-box commodity-examine">
      <GoBack history={this.props.history} title="新建拼团活动" />
      <Form style={{ marginTop: 20 }} ref={this.formRef}
        initialValues={initialValues}
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 22 }}
        onFinish={(values) => this.onFinish(values)}
        autoComplete="off"
      >
        <Form.Item
          label="活动名称"
          name="activityName"
          rules={[
            {
              required: true,
              message: '请输入活动名称!',
            },
          ]}
        >
          <Input style={{ width: "400px" }} maxLength={30} />
        </Form.Item>

        <Form.Item
          label="活动时间"
          name="activityTime"
          rules={[
            {
              required: true,
              message: '请选择未来的时间范围！',
            },
          ]}
        >
          <RangePicker
            // disabledDate={this.disabledDate}
            format="YYYY-MM-DD HH:mm" style={{
              width: 400,
            }} showTime />
        </Form.Item>
        <Form.Item
          label="成团时间"
          name="teamPeriod"
          rules={[
            {
              required: true,
              message: '请填写不超过72的正整数！',
            },
          ]}
        >
          <InputNumber addonBefore="发起后" addonAfter="小时内有效" min={1} max={72} precision={0} style={{ width: "400px" }} />
        </Form.Item>
        <Form.Item
          label="成团人数"
          name="teamSize"
          rules={[
            {
              required: true,
              message: '请填2~99之间的整数！',
            },
          ]}
        >
          <InputNumber max={99} min={2} precision={0} style={{ width: "400px" }} addonAfter="人" />
        </Form.Item>

        <Form.Item
          label="商品"
          name="goods"
          rules={[
            {
              required: mode !== 'view',
              validator: this.checkGoods.bind(this)
            }
          ]}
        >
          <Goods ref={this.GoodsRef} mode={mode} activityId={activityId} disabledKeys={disabledKeys} getFieldsValue={(key, isCheck) => this.getFieldsValue(key, isCheck)}></Goods>
        </Form.Item>
        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Button type="default" onClick={() => this.props.history.go(-1)} style={{ 'marginRight': 20 }}>
            取消
          </Button>
          <Button type="primary" htmlType="submit">
            确定
          </Button>
        </Form.Item>
      </Form>
    </div>)
  }
}

export default SpellTogetherAdd
